package com.fei.leyou.controller;

import com.fei.leyou.config.JwtProperties;
import com.fei.leyou.search.utils.CookieUtils;
import com.fei.leyou.service.AuthService;
import com.fei.user.pojo.UserDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Resource
    private JwtProperties prop;

    /**
     * 登录授权

     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(@RequestBody UserDTO dto,
            HttpServletRequest request,
            HttpServletResponse response) {
        // 登录校验
        String token = this.authService.authentication(dto.getUsername(), dto.getPassword());
        if (StringUtils.isBlank(token)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
        CookieUtils.setCookie(request, response, prop.getPriKeyPath(),
                token, prop.getExpire(), null, true);
        return ResponseEntity.ok().build();
    }
}
